import config from "../config";
import position from "../service/position";

// canvas抽象类 定义canvsd的公共方法和抽象属方法
export default abstract class canvasAbstract {
  modelist: IModel[] = [];
  abstract num(): number;
  abstract model(): ModelInterface | BulletModelInterface;
  protected app = document.querySelector<HTMLDivElement>("#app")!;
  protected el = document.createElement('canvas');
  public canvas = this.el.getContext('2d')!;
  constructor(
    public name: string
  ) {
    // 创建canvas
    this.createCanvas();
  };
  protected createCanvas() {
    this.el.width = config.canvas.width;
    this.el.height = config.canvas.hieght;
    this.el.setAttribute('name', this.name);
    this.app.insertAdjacentElement('afterbegin', this.el);
  };

  //创建模型 --- 创建与渲染分离是为了防止运动重新绘制重复绘制模型实例
  protected createModel() {
    // 遍历坐标list创建并绘制对应模型
    position.positionCollection(this.num()).forEach(pos => {
      let model = this.model() as ModelInterface;
      let instance = new model(pos.x, pos.y);
      this.modelist.push(instance);
    });
  };
  // 渲染模型
  public renderModel() {
    // 遍历绘制对应模型
    this.canvas.clearRect(0, 0, config.canvas.width, config.canvas.hieght);
    this.modelist.forEach(item => {
      item.render();
    });
  };
  // 销毁模型的方法
  removeModels(model: IModel) {
    this.modelist = this.modelist.filter(item => {
      return model !== item;
    });
  }
}